const mysql = require('mysql2/promise')
const config = require('./config')

// 简化的模拟数据
const mockNovels = [
  {
    id: 1,
    title: '斗破苍穹',
    author: '天蚕土豆',
    author_id: 1,
    cover_url:
      'https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=300&h=400&fit=crop',
    description:
      '这里是斗气大陆，没有花俏的魔法，有的，仅仅是繁衍到巅峰的斗气！在这里，斗气就是一切！',
    category: 'fantasy',
    status: 'completed',
    word_count: 5400000,
    chapter_count: 1648,
    rating: 4.6,
    rating_count: 89234,
    view_count: 12500000,
    favorite_count: 345678,
    tags: JSON.stringify(['玄幻', '热血', '升级流', '经典']),
    is_vip: true,
    price: 299,
    last_chapter_title: '大结局：斗帝归来',
    last_chapter_time: '2023-08-20 15:30:00'
  },
  {
    id: 2,
    title: '斗罗大陆',
    author: '唐家三少',
    author_id: 7,
    cover_url:
      'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop',
    description:
      '唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。',
    category: 'fantasy',
    status: 'completed',
    word_count: 8888772,
    chapter_count: 336,
    rating: 4.8,
    rating_count: 298765,
    view_count: 45600000,
    favorite_count: 1234567,
    tags: JSON.stringify(['玄幻', '武魂', '穿越', '经典', '唐家三少']),
    is_vip: true,
    price: 399,
    last_chapter_title: '第三百三十六章 成神（大结局）',
    last_chapter_time: '2009-12-13 20:00:00'
  },
  {
    id: 3,
    title: '完美世界',
    author: '辰东',
    author_id: 2,
    cover_url:
      'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=300&h=400&fit=crop',
    description:
      '一粒尘可填海，一根草斩尽日月星辰，弹指间天翻地覆。群雄并起，万族林立，诸圣争霸，乱天动地。',
    category: 'fantasy',
    status: 'ongoing',
    word_count: 6200000,
    chapter_count: 1890,
    rating: 4.8,
    rating_count: 156789,
    view_count: 28900000,
    favorite_count: 567890,
    tags: JSON.stringify(['玄幻', '无敌流', '热血', '经典']),
    is_vip: true,
    price: 399,
    last_chapter_title: '第1890章：仙域风云',
    last_chapter_time: '2024-01-15 09:00:00'
  },
  {
    id: 4,
    title: '都市之超级医圣',
    author: '叶天南',
    author_id: 3,
    cover_url:
      'https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?w=300&h=400&fit=crop',
    description:
      '一代医圣重生都市，凭借前世的医术和修为，在都市中纵横捭阖，谱写传奇人生。',
    category: 'urban',
    status: 'ongoing',
    word_count: 3200000,
    chapter_count: 980,
    rating: 4.3,
    rating_count: 45678,
    view_count: 8900000,
    favorite_count: 234567,
    tags: JSON.stringify(['都市', '医术', '重生', '爽文']),
    is_vip: false,
    price: 0,
    last_chapter_title: '第980章：医圣威名',
    last_chapter_time: '2024-01-10 14:20:00'
  },
  {
    id: 5,
    title: '霸道总裁的小娇妻',
    author: '我吃西红柿',
    author_id: 4,
    cover_url:
      'https://images.unsplash.com/photo-1544716278-ca5e3f4abd8c?w=300&h=400&fit=crop',
    description:
      '她是豪门千金，却被家族抛弃。他是商界霸主，冷酷无情却独独对她温柔...',
    category: 'romance',
    status: 'completed',
    word_count: 1800000,
    chapter_count: 567,
    rating: 4.2,
    rating_count: 78901,
    view_count: 15600000,
    favorite_count: 456789,
    tags: JSON.stringify(['都市', '总裁', '甜宠', '豪门']),
    is_vip: true,
    price: 199,
    last_chapter_title: '第567章：幸福终章',
    last_chapter_time: '2023-11-28 16:45:00'
  }
]

async function simpleMigrate () {
  try {
    const connection = await mysql.createConnection({
      host: config.database.host,
      port: config.database.port,
      user: config.database.user,
      password: config.database.password,
      database: config.database.name
    })

    console.log('🚀 开始简化迁移...')

    // 1. 更新现有小说数据
    console.log('\n📚 更新小说数据...')

    for (const novel of mockNovels) {
      // 检查小说是否存在
      const [existing] = await connection.execute(
        'SELECT id FROM novels WHERE id = ?',
        [novel.id]
      )

      if (existing.length > 0) {
        // 更新现有记录
        await connection.execute(
          `
          UPDATE novels SET 
            title = ?, author = ?, author_id = ?, cover_url = ?, description = ?,
            category = ?, status = ?, word_count = ?, chapter_count = ?, rating = ?,
            rating_count = ?, view_count = ?, favorite_count = ?, tags = ?,
            is_vip = ?, price = ?, last_chapter_title = ?, last_chapter_time = ?
          WHERE id = ?
        `,
          [
            novel.title,
            novel.author,
            novel.author_id,
            novel.cover_url,
            novel.description,
            novel.category,
            novel.status,
            novel.word_count,
            novel.chapter_count,
            novel.rating,
            novel.rating_count,
            novel.view_count,
            novel.favorite_count,
            novel.tags,
            novel.is_vip,
            novel.price,
            novel.last_chapter_title,
            novel.last_chapter_time,
            novel.id
          ]
        )
        console.log(`✅ 更新: ${novel.title}`)
      } else {
        // 插入新记录
        await connection.execute(
          `
          INSERT INTO novels (
            id, title, author, author_id, cover_url, description, category, status,
            word_count, chapter_count, rating, rating_count, view_count, favorite_count,
            tags, is_vip, price, last_chapter_title, last_chapter_time
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `,
          [
            novel.id,
            novel.title,
            novel.author,
            novel.author_id,
            novel.cover_url,
            novel.description,
            novel.category,
            novel.status,
            novel.word_count,
            novel.chapter_count,
            novel.rating,
            novel.rating_count,
            novel.view_count,
            novel.favorite_count,
            novel.tags,
            novel.is_vip,
            novel.price,
            novel.last_chapter_title,
            novel.last_chapter_time
          ]
        )
        console.log(`✅ 插入: ${novel.title}`)
      }
    }

    // 2. 插入一些章节数据
    console.log('\n📄 插入章节数据...')

    const chapters = [
      {
        novel_id: 1,
        chapter_number: 1,
        title: '第一章：废物？',
        content: '萧炎，萧家最年轻的斗之气三段的天才...',
        word_count: 3200,
        is_vip: false,
        price: 0
      },
      {
        novel_id: 1,
        chapter_number: 2,
        title: '第二章：退婚',
        content: '美杜莎女王驾到...',
        word_count: 3400,
        is_vip: false,
        price: 0
      },
      {
        novel_id: 2,
        chapter_number: 1,
        title: '第一章：唐门暗器',
        content: '唐三，唐门外门弟子...',
        word_count: 2800,
        is_vip: false,
        price: 0
      },
      {
        novel_id: 3,
        chapter_number: 1,
        title: '第一章：仙村',
        content: '大荒深处，群山万壑...',
        word_count: 3600,
        is_vip: false,
        price: 0
      }
    ]

    for (const chapter of chapters) {
      try {
        await connection.execute(
          `
          INSERT INTO chapters (novel_id, chapter_number, title, content, word_count, is_vip, price)
          VALUES (?, ?, ?, ?, ?, ?, ?)
          ON DUPLICATE KEY UPDATE title = VALUES(title), content = VALUES(content)
        `,
          [
            chapter.novel_id,
            chapter.chapter_number,
            chapter.title,
            chapter.content,
            chapter.word_count,
            chapter.is_vip,
            chapter.price
          ]
        )
        console.log(`✅ 章节: ${chapter.title}`)
      } catch (error) {
        if (error.code !== 'ER_DUP_ENTRY') {
          console.log(`⚠️ 插入章节失败: ${error.message}`)
        }
      }
    }

    // 3. 显示最终结果
    console.log('\n📊 迁移完成，检查结果...')
    const [finalNovels] = await connection.execute(`
      SELECT n.id, n.title, n.author, n.category, n.status, n.rating, n.view_count, n.is_vip
      FROM novels n 
      ORDER BY n.id
      LIMIT 10
    `)
    console.table(finalNovels)

    const [chapterCount] = await connection.execute(
      'SELECT COUNT(*) as total FROM chapters'
    )
    console.log(`\n📄 总章节数: ${chapterCount[0].total}`)

    await connection.end()
    console.log('\n🎉 简化迁移完成！')
  } catch (error) {
    console.error('❌ 迁移失败:', error.message)
    console.error(error)
  }
}

simpleMigrate()
